
//
//  SpecialMessageViewController.m
//  WisdomZhuHai
//
//  Created by yewei on 14-10-24.
//  Copyright (c) 2014年 wyd. All rights reserved.
//
//首页资讯列表
#import "SpecialMessageViewController.h"
#import "Common.h"
#import "UIImageView+WebCache.h"
#import "SpecialDetailViewController.h"
#import "RNFrostedSidebar.h"
#import "SportsDetailViewController.h"
#import "FirstViewController.h"
#import "GoodDetailViewController.h"
#import "CommonCellViewController.h"
#import "TransforController.h"
#import "MovieViewController.h"
#import "EmptyViewController.h"
#import "SiftCellViewController.h"
#import "GlobalCellViewController.h"
#import "BMapKit.h"
#import "TopSpecialCellViewController.h"
#import "stdbool.h"
#import "TopSpecialDetailViewControlleViewController.h"
#import "webViewPushDiscloseDetailsViewController.h"
#import "BableWebViewController.h"
#import "TopSpecialDetailsPageTableViewController.h"


static const CGSize OKCOMMENDVIEW_SIZE = {152, 68};
static const CGFloat OKCOMMENDCELL_HEIGHT = 184;
static const CGFloat OKCOMMENDCELL_HEIGHT_2 = 100;

@interface SpecialMessageViewController()<UIScrollViewDelegate, BMKLocationServiceDelegate> {
    BMKLocationService* _locService;
}

@property (nonatomic,strong) NSDictionary *specialDataDic; //专题相关数据
@property (nonatomic,strong) NSDictionary *messageDataDic; //资讯相关数据
@property (nonatomic,strong) NSMutableArray *newsList; //资讯列表
@property (nonatomic,retain) UIView* cntView;       //幻灯片视图容器
@property (nonatomic,retain) HXLCustomPageView *pageScroll;  //幻灯片视图控件
@property (nonatomic,retain) NSTimer *timer;
@property (nonatomic,retain) UIScrollView* seasonScroll;//当季热门scrollview
@property int messageIconQueueID;
@property int specialImgQueueID;
@property int messageIndex; //资讯游标,指向下一页数据的第一条，例如当前20条，则指向21
@property (nonatomic,strong) NSString *updateUrl;
@property (nonatomic, strong)UITableViewCell* cell;
@property (nonatomic, assign) int gotoCheckLogin;
@property (nonatomic, assign) int localTime;
@property (nonatomic,strong) NSString *isTopic;
@property (nonatomic,strong)BableWebViewController *web;

@property (nonatomic,strong)NSDictionary *topSpecialDicData;
@property (nonatomic,strong)TopSpecialDetailsPageTableViewController *sub;

-(void)pageStartRoll;
-(void)pageEndRoll;
-(void)pageRolling;
-(void)startDownloadSpecialImage;

@end

@implementation SpecialMessageViewController

const float MESSAGE_CELL_HEIGHT = 85;   //与xib中一致
const float MESSAGE_SPECIAL_CELL_HEIGHT = 98;//资讯列表中专题cell的高度（与TopSpecialCellViewController.xib中一致）
const float SEASON_HEIGHT = 100;
const float MESSAGE_PAGE_COUNT = 20;  //资讯一页请求的个数

-(void)didFinishGetUpdateInfo:(NSDictionary *)dic
{
    if(dic == nil)
    {
        NSLog(@"SpecialMessageViewController didFinishGetUpdateInfo dic is nil");
        return;
    }
    NSString *version = [Common valueForKey:P_NUM dic:dic];
    self.updateUrl = [Common valueForKey:P_URL dic:dic];
    if([Common isNewAppVersion:version])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"有新的版本可供下载，是否立即更新" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        [alert show];
        
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        [[UIApplication sharedApplication] openURL:[Common getUrlByString:self.updateUrl]];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.gotoCheckLogin = 0;
    // Do any additional setup after loading the view.
    self.tableView.frame = CGRectMake(0, -45, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 70);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.1)];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.tableView.bounds.size.width, 0)];
    self.tableView.backgroundColor = [Common colorWithRGB:0xdbdcdc];
    self.tableView.delegate = self;
    [self setEnableRefresh:YES];
    [self setEnableLoadMore:YES];
    self.pullTableViewDelegate = self;
    self.cntView = [[UIView alloc] initWithFrame:self.frame];
    //获取数据
    [[ProtocolManager shareInstance] getSlidesAndSpecial:self selector:@selector(didFinishGetSlidesAndSpecial:)];
//    [[ProtocolManager shareInstance] getMessageList:-1 topicId:-1 returnCount:MESSAGE_PAGE_COUNT beginNo:0 target:self selector:@selector(didFinishGetMessageList:)];
    [[ProtocolManager shareInstance] getHomePageNewsList:20 beginNo:0 target:self selector:@selector(didFinishGetNewsList:)];
    self.messageIndex = 1;

    //检查新版本
    [[ProtocolManager shareInstance] getUpdateInfo:self selector:@selector(didFinishGetUpdateInfo:)];
}

- (void)openLocation {
    //设置定位精确度，默认：kCLLocationAccuracyBest
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100.f];
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
}

//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [ProtocolManager shareInstance].latitude = userLocation.location.coordinate.latitude;
    [ProtocolManager shareInstance].longitude = userLocation.location.coordinate.longitude;
    _localTime = 1;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    NSLog(@"视图滚动中y轴坐标%f",self.tableView.contentOffset.y);
    [self.delegate changeHeadViewAlpha:self.tableView.contentOffset.y];
}

-(void)showSlidesAndSpecialView
{
    //专题滚动页面（图片）
    float y = 0.0;
    NSArray *slidesList = [Common valueForKey:P_SLIDESLIST dic:self.specialDataDic];
//    NSMutableArray *pageImgs = [NSMutableArray array];
//    for(int i = 0 ; i < [slidesList count]; ++i)
//    {
//        [pageImgs addObject:DEFAULT_IMAGE_640];
//    }
    NSMutableArray *imgViews = [[NSMutableArray alloc]init];
//    UIImage *tempImg = [UIImage imageNamed:[pageImgs objectAtIndex:0]];
//    float imgWidth = tempImg.size.width;
//    float imgHeight = tempImg.size.height;
//    float rate = 4 / 5.0;
    float pageWidth = self.view.frame.size.width;
    float pageHeight = 160;
    CGRect scrollFrame = CGRectMake(0, y, pageWidth, pageHeight);
    for(int i = 0; i < [slidesList count]; ++i)
    {
 //       NSString *imgName = [pageImgs objectAtIndex:i];
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, scrollFrame.size.width, scrollFrame.size.height)];
        //        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imgView.image = nil;//[UIImage imageNamed:imgName];
        [imgViews addObject:imgView];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];
        label.backgroundColor = [UIColor clearColor];
        NSDictionary *topNewsDic = [slidesList objectAtIndex:i];
        label.text = [topNewsDic valueForKey:P_BRIEFINTRO];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textAlignment = NSTextAlignmentCenter;
        CGSize size = [Common textSizeWithFont:label.font constrainedToSize:CGSizeMake(imgView.bounds.size.width, MAXFLOAT) string:@"a"];
        label.textColor = [UIColor whiteColor];
        label.frame = CGRectMake(0, imgView.bounds.size.height - size.height - 20, imgView.bounds.size.width, size.height);
        [imgView addSubview:label];
    }
    [self.pageScroll removeFromSuperview];
    self.pageScroll = [[HXLCustomPageView alloc]initPageViewWithFrame:scrollFrame views:imgViews selectType:HXLCustomScrollView_SelectType_CanSelected];
    [self.pageScroll setPageControlTouchEnable:NO];
    self.pageScroll.pageViewDelegate = self;
    [self.cntView addSubview:self.pageScroll];
    self.cntView.frame = CGRectMake(0, 0, self.cntView.frame.size.width,scrollFrame.size.height);
    [self startDownloadSpecialImage];
    self.messageIconQueueID = 0;
}

-(void)didFinishGetSlidesAndSpecial:(NSDictionary *)dic
{
    if(dic == nil)
    {
        NSLog(@"didFinishGetSlidesAndSpecial dic is nil");
        return;
    }
    NSLog(@"didFinishGetSlidesAndSpecial dic %@",dic);
    self.specialDataDic = dic;
    [ProtocolManager shareInstance].telephone = [Common valueForKey:@"telphone" dic:dic];
    [self showSlidesAndSpecialView];
    [self.tableView reloadData];
    self.gotoCheckLogin++;
    if (self.gotoCheckLogin == 2){
        [self gotoCheckIfLogin];
    }
}

-(void)didFinishGetNewsList:(NSDictionary *)dic
{
    if(dic == nil)
    {
        NSLog(@"didFinishGetMessageList dic is nil");
        return;
    }
    NSLog(@"didFinishGetMessageList dic %@",dic);
    [self resetPullTableViewState];
    NSArray *list = [Common valueForKey:P_V2_NEWS dic:dic];
    if([list count] == 0)
    {
        //已经加载完全部内容
        [self setEnableLoadMore:NO];
        return;
    }
    if(self.newsList == nil)
    {
        self.newsList = [NSMutableArray arrayWithArray:list];
    }
    else
    {
        [self.newsList addObjectsFromArray:list];
    }
    self.messageIndex += [list count];
    if([list count] < MESSAGE_PAGE_COUNT)
    {
        //已经加载完全部内容
        [self setEnableLoadMore:NO];
    }
    else
    {
        [self setEnableLoadMore:YES];
    }
    self.gotoCheckLogin++;
    [self.tableView reloadData];
    if (self.gotoCheckLogin == 2){
        [self gotoCheckIfLogin];
    }
}

- (void)gotoCheckIfLogin{
    [[TransforController sharedInstanceOfThirdViewController]doCheckIfLogined];
}

-(void)startDownloadSpecialImage
{
    //下载幻灯片图片
    self.specialImgQueueID = [[HttpRequestManager getSharedInstance] createHttpRequestQueue:self];
    NSArray *slidesList = [Common valueForKey:P_SLIDESLIST dic:self.specialDataDic];
    for(int i = 0; i < [slidesList count]; ++i)
    {
        NSDictionary *dic = [slidesList objectAtIndex:i];
        NSString *url = [Common valueForKey:P_COVER_PATH dic:dic];
        NSLog(@"special image url = %@",url);
        [[HttpRequestManager getSharedInstance] addHttpRequestToQueue:self.specialImgQueueID Url:[Common getFullDownloadPathByRelativePath:url] ToPath:nil UserInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"specialImage",@"type",[NSNumber numberWithInt:i],@"index", nil] Delegate:self];
    }
    
}

-(void)pageStartRoll
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(pageRolling) userInfo:nil repeats:YES];
}
-(void)pageEndRoll
{
    [self.timer invalidate];
    self.timer = nil;
}

-(void)pageRolling
{
    [self.pageScroll nextPage];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self pageStartRoll];
    [self openLocation];
    [[HttpRequestManager getSharedInstance] setSuspended:NO ForQueue:self.specialImgQueueID];
    [[HttpRequestManager getSharedInstance] setSuspended:NO ForQueue:self.messageIconQueueID];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self pageEndRoll];
    [_locService stopUserLocationService];
    [[HttpRequestManager getSharedInstance] setSuspended:YES ForQueue:self.specialImgQueueID];
    [[HttpRequestManager getSharedInstance] setSuspended:YES ForQueue:self.messageIconQueueID];
}

-(void)specialButton:(UIButton *)button
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
}

-(void)seasonSetup:(UITableViewCell *)cell
{
    NSDictionary* seasonDic = [Common valueForKey:P_SEASONLIST dic:self.specialDataDic];
    if (seasonDic == NULL) {
        return;
    }
    self.seasonScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, SEASON_HEIGHT)];
    self.seasonScroll.backgroundColor = [UIColor redColor];
    int i = 0;
    int j = 1;
    CGFloat temp = 35;
    for (NSDictionary *season in seasonDic) {
        if (i == 4) {
            temp += 35;
            j++;
        }
        NSString *imgUrl = [Common valueForKey:P_COVER_PATH dic:season];
        NSString *name = [Common valueForKey:P_NAME dic:season];
        UIView *seasonView = [[UIView alloc] initWithFrame:CGRectMake(temp, 0, 50, SEASON_HEIGHT)];
        UIImageView *seasonImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, SEASON_HEIGHT/3, 40, 40)];
        [seasonImage setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
        [seasonView addSubview:seasonImage];
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, SEASON_HEIGHT/4*3, 40, 20)];
        nameLabel.font = [UIFont fontWithName:@"Arial" size:10.0];
        nameLabel.textColor = [Common colorWithRGB:0x7f7f7f];
        nameLabel.textAlignment = UITextAlignmentCenter;
        nameLabel.text = name;
        [seasonView addSubview:nameLabel];
        UITapGestureRecognizer *onTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSeason:)];
        seasonView.tag = 10000 + i;
        [seasonView setAccessibilityValue:@"season"];
        [seasonView addGestureRecognizer:onTap];
        [self.seasonScroll addSubview:seasonView];
        i++;
        temp += 70;
    }
    [self.seasonScroll setContentSize:CGSizeMake(j * 320, SEASON_HEIGHT)];
    [self scrollVIewCellConfig:self.seasonScroll];
    [cell addSubview:self.seasonScroll];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 100, 20)];
    titleLabel.font = [UIFont fontWithName:@"Arial" size:15.0];
    titleLabel.textColor = [Common colorWithRGB:0xb2b2b2];
    titleLabel.text = @"当季热门";
    [cell addSubview:titleLabel];
    
    if ([seasonDic count] > 4) {
        UIView *pageDotView = [[UIView alloc] initWithFrame:CGRectMake(290, 10, 5, 5)];
        UIImageView *firstDot = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, pageDotView.frame.size.width, pageDotView.frame.size.height)];
        UIImageView *secondDot = [[UIImageView alloc] initWithFrame:CGRectMake(8, 0, pageDotView.frame.size.width, pageDotView.frame.size.height)];
        firstDot.image = [UIImage imageNamed:@"siftSideBar/dot_blue"];
        secondDot.image = [UIImage imageNamed:@"siftSideBar/dot_grey"];
        [pageDotView addSubview:firstDot];
        [pageDotView addSubview:secondDot];
        firstDot.tag = 30001;
        secondDot.tag = 30002;
        [cell addSubview:pageDotView];
    }
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, SEASON_HEIGHT-0.5, cell.bounds.size.width, 0.5)];
    lineView.backgroundColor = [Common colorWithRGB:0xcccccc];
    [cell addSubview:lineView];
}

- (void)scrollVIewCellConfig:(UIScrollView*)Scroll
{
    //设置委托
    Scroll.delegate = self;
    //设置背景颜色
    Scroll.backgroundColor = [Common colorWithRGB:0xFFFFFF];
    //设置取消触摸
    Scroll.canCancelContentTouches = NO;
    //设置滚动条类型
    Scroll.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    //是否自动裁切超出部分
    Scroll.clipsToBounds = YES;
    //控制控件是否能滚动
    Scroll.scrollEnabled = YES;
    //设置是否可以进行画面切换
    Scroll.pagingEnabled = YES;
    //设置在拖拽的时候是否锁定其在水平或者垂直的方向
    Scroll.directionalLockEnabled = NO;
    //隐藏滚动条设置（水平、跟垂直方向）
    Scroll.alwaysBounceHorizontal = NO;
    Scroll.alwaysBounceVertical = NO;
    Scroll.showsHorizontalScrollIndicator = NO;
    Scroll.showsVerticalScrollIndicator = NO;
    
    Scroll.canCancelContentTouches = YES;
    Scroll.delaysContentTouches = YES;
}

-(void)okRecommend:(UITableViewCell*)cell indexPath:(NSIndexPath*)indexPath
{
    NSArray *okList = [Common valueForKey:P_OKLIST dic:self.specialDataDic];
    if (okList.count <= 0) {
        return;
    }
    cell.contentView.backgroundColor = [Common colorWithRGB:0xf9f9f9];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 100, 20)];
    titleLabel.font = [UIFont fontWithName:@"Arial" size:15.0];
    titleLabel.textColor = [Common colorWithRGB:0xb2b2b2];
    titleLabel.text = @"OK推荐";
    [cell addSubview:titleLabel];
    for (UIView *view in cell.contentView.subviews) {
        if (view.tag >= 1000) {
            [view removeFromSuperview];
        }
    }
    CGFloat intervalX = (cell.contentView.frame.size.width - OKCOMMENDVIEW_SIZE.width*2)/3;
    for (int i = 0; i < okList.count; i++) {
        NSDictionary* dic = okList[i];
        NSString *logo = [Common valueForKey:P_COVER_PATH dic:dic];
        NSString *name = [Common valueForKey:P_NAME dic:dic];
        NSString *description = [Common valueForKey:P_DESCRIPTION dic:dic];
        NSString *color = [Common valueForKey:P_V2_RGB dic:dic];
        UIView* view = [self createOkRecommendView:logo title:name description:description color:color];
        view.tag = 20000 + i;
        
        CGRect frame = view.frame;
        frame.origin.x = intervalX * 1 + i * (OKCOMMENDVIEW_SIZE.width+intervalX);
        frame.origin.y = 32;
        if (i >= 2) {
            frame.origin.x = intervalX * 1 + (i - 2) * (OKCOMMENDVIEW_SIZE.width+intervalX);
            frame.origin.y = 32 + OKCOMMENDVIEW_SIZE.height + intervalX;
        }
        view.frame = frame;
        UITapGestureRecognizer *onTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSeason:)];
        [view addGestureRecognizer:onTap];
        [view setAccessibilityValue:@"OK"];
        [cell.contentView addSubview:view];
    }
    UIView *lineView = nil;
    if (okList.count > 2) {
        lineView = [[UIView alloc] initWithFrame:CGRectMake( 5, OKCOMMENDCELL_HEIGHT - 0.5, cell.bounds.size.width - 10, 0.5)];
    } else {
        lineView = [[UIView alloc] initWithFrame:CGRectMake( 5, OKCOMMENDCELL_HEIGHT_2 - 0.5, cell.bounds.size.width - 10, 0.5)];
    }
    lineView.backgroundColor = [Common colorWithRGB:0xcccccc];
    [cell.contentView addSubview:lineView];
}

- (UIView*)createOkRecommendView:(NSString*)logo title:(NSString*)title description:(NSString*)description color:(NSString*)color
{
    UIView *okRView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, OKCOMMENDVIEW_SIZE.width, OKCOMMENDVIEW_SIZE.height)];
    okRView.backgroundColor = [UIColor whiteColor];
    okRView.layer.borderWidth = 0.5;
    okRView.layer.borderColor = [[Common colorWithRGB:0xcccccc] CGColor];
    UIImageView *okImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, OKCOMMENDVIEW_SIZE.height - 20, OKCOMMENDVIEW_SIZE.height-20)];
    [okImg setImageWithURL:[Common getFullDownloadPathByRelativePath:logo] placeholderImage:[Common getPlaceholderImage:ePIT_StoreLogo]];
    
    UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(OKCOMMENDVIEW_SIZE.height, 15, OKCOMMENDVIEW_SIZE.width - OKCOMMENDVIEW_SIZE.height, OKCOMMENDVIEW_SIZE.height/3)];
    lbTitle.font = [UIFont fontWithName:@"Arial" size:13.0];
    lbTitle.textColor = [UIColor blackColor];
    lbTitle.text = title;
    
    UILabel *lbIntro = [[UILabel alloc] initWithFrame:CGRectMake(OKCOMMENDVIEW_SIZE.height, OKCOMMENDVIEW_SIZE.height/3 + 10, OKCOMMENDVIEW_SIZE.width - OKCOMMENDVIEW_SIZE.height, OKCOMMENDVIEW_SIZE.height/3)];
    NSArray *rgbArray = [color componentsSeparatedByString:@"#"];
    NSString *rgb = nil;
    if ( rgbArray.count < 2) {
        rgb = [NSString stringWithFormat:@"%@%@", @"0x",@"b2b2b2"];
    } else {
        rgb = [NSString stringWithFormat:@"%@%@", @"0x",rgbArray[1]];
    }
    unsigned int colorInt = strtoul([rgb UTF8String],0,0);//nsstring 转 rgb
    lbIntro.font = [UIFont fontWithName:@"Arial" size:10.0];
    lbIntro.textColor = [Common colorWithRGB:colorInt];
    lbIntro.text = @"OK珠海推荐";
    if (description.length > 0) {
        lbIntro.text = description;
    }
    
    [okRView addSubview:okImg];
    [okRView addSubview:lbTitle];
    [okRView addSubview:lbIntro];
    return okRView;
}

#pragma mark - cell
- (void)cellSetup:(UITableViewCell*)cell index:(NSInteger)index;
{
    cell.contentView.backgroundColor = [Common colorWithRGB:0xf9f9f9];
    if (self.newsList.count <= 0) {
        return;
    }
    
    NSDictionary *cellDic = _newsList[index];
//    //-Bable
//    self.isTopic = [Common valueForKey:P_IS_TOPIC dic:cellDic];
//    if([[cellDic objectForKey:P_IS_TOPIC] isEqual: @(YES)]){//判断是否为专题内容
//        NSLog(@"载入专题CELL isTopic=%@ 测试测试测试测试测试。。。。。。。。。",_isTopic);
//        TopSpecialCellViewController *topic = [[TopSpecialCellViewController alloc] init];
//        [topic cellSetup:cell dic:cellDic index:index];
//    }//Bable-
//    else{
    NSString *imgUrl = [Common valueForKey:P_NPHOTO dic:cellDic];
    NSString *title = [Common valueForKey:P_NRTITLE dic:cellDic];
    NSArray *tagsList = [Common valueForKey:P_TAGS dic:cellDic];
    NSString *source_name = [Common valueForKey:P_V2_SOURCE_NAME dic:cellDic];
    NSString *comment_cnt = [Common valueForKey:P_V2_COMMENT_CNT dic:cellDic];
    NSString *date = [Common valueForKey:P_UPDATED_TIME dic:cellDic];
    UIImageView *image = (UIImageView*)[cell viewWithTag:1001];
    [image setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
    UIImageView *okImage = (UIImageView*)[cell viewWithTag:1007];
    okImage.hidden = YES;
    
//    TableViewController *tvc = [[TableViewController alloc] init];
//    UITableView *table = (UITableView*)[self.view viewWithTag:123];
    
    UILabel *titleLab = (UILabel*)[cell viewWithTag:1002];
    [titleLab setNumberOfLines:2];
    titleLab.text = title;
    [titleLab sizeToFit];    
    CGRect frame = titleLab.frame;
    frame.size.width = 216;
    titleLab.frame = frame;
    
    [self tagSetup:tagsList titleLabHeight:frame.size.height cell:cell];
    UILabel *price = (UILabel*)[cell viewWithTag:1005];
    [price removeFromSuperview];
    UIImageView *districtNameImg = (UIImageView*)[cell viewWithTag:2001];
    [districtNameImg removeFromSuperview];
    UILabel *districtNameLab = (UILabel*)[cell viewWithTag:2002];
    districtNameLab.text = [NSString stringWithFormat:@"%@ %@", [date componentsSeparatedByString:@" "][0],source_name ];
    UIImageView* goodImg = (UIImageView*)[cell viewWithTag:2003];
    [goodImg removeFromSuperview];
    UILabel* CommontLab = (UILabel*)[cell viewWithTag:2006];
    CommontLab.text = comment_cnt;
        
//    }
}

//标签描绘
- (void)tagSetup:(NSArray*)tagsList titleLabHeight:(CGFloat)height cell:(UITableViewCell*)cell
{
    if(tagsList.count <= 0)
    {
        return;
    }
    CGFloat tagX = 0.0;
    for (int i = 0; i < [tagsList count]; i++) {
        UIView* tagListView = nil;
        if (height < 20.0) {
            tagListView = [cell viewWithTag:1003];
        } else {
            tagListView = [cell viewWithTag:1004];
        }
        NSDictionary *tagDic = tagsList[i];
        NSArray *rgbArray = [[Common valueForKey:P_V2_RGB dic:tagDic] componentsSeparatedByString:@"#"];
        NSString *rgb = nil;
        if ( rgbArray.count < 2) {
            rgb = [NSString stringWithFormat:@"%@%@", @"0x",@"18aaf6"];
        } else {
            rgb = [NSString stringWithFormat:@"%@%@", @"0x",rgbArray[1]];
        }
        NSString *name = [Common valueForKey:P_NAME dic:tagDic];
        UIView *tagView = [[UIView alloc] initWithFrame:CGRectMake(tagX, 0, 45, 16)];
        tagView.layer.cornerRadius = 3.0;
        unsigned int color = strtoul([rgb UTF8String],0,0);//nsstring 转 rgb
        tagView.backgroundColor = [Common colorWithRGB:color];
        UILabel *tagNameLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tagView.frame.size.width, tagView.frame.size.height)];
        tagNameLab.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:10.0];
        tagNameLab.textAlignment = UITextAlignmentCenter;
        tagNameLab.textColor = [UIColor whiteColor];
        tagNameLab.text = name;
        [tagView addSubview:tagNameLab];
        [tagListView addSubview:tagView];
        tagX += 50;
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *okList = [Common valueForKey:P_OKLIST dic:self.specialDataDic];
    NSArray* seasonList = [Common valueForKey:P_SEASONLIST dic:self.specialDataDic];
    if (section == 0) {
        if (okList.count > 0 && seasonList.count > 0){
            return 3;
        } else if (okList.count <= 0 && seasonList.count <= 0) {
            return 1;
        } else {
            return 2;
        }
    } else {
        return [self.newsList count];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{   //CELL尺寸判断器
    NSArray *okList = [Common valueForKey:P_OKLIST dic:self.specialDataDic];
    if (indexPath.section == 0) {
        if(indexPath.row == 0)
        {
            return self.cntView.frame.size.height;
        }
        else if(indexPath.row == 1)
        {
            //专题标题
            return SEASON_HEIGHT;
        }
        else if(indexPath.row == 2)
        {
            //专题看点
            if (okList.count > 2)
            {
                return OKCOMMENDCELL_HEIGHT;
            } else {
                return OKCOMMENDCELL_HEIGHT_2;
            }
        }
    }
    else
    {
        //资讯列表中的专题
        NSDictionary *cellDic = _newsList[indexPath.row];
        if([[cellDic objectForKey:P_IS_TOPIC] isEqual: @(YES)]){
            return MESSAGE_SPECIAL_CELL_HEIGHT;
        }
        //资讯
        return MESSAGE_CELL_HEIGHT;
    }
    return tableView.rowHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 30;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return 0;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
    view.backgroundColor = [Common colorWithRGB:0xf9f9f9];
    if (section == 1) {
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 100, 20)];
        lb.backgroundColor = [UIColor clearColor];
        lb.textColor = [Common colorWithRGB:0xb2b2b2];
        lb.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:15.0];
        lb.text = @"资讯列表";
        [view addSubview:lb];
        UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake( 5, 29, 310, 1)];
        bottomLine.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:1.0];;
        [view addSubview:bottomLine];
    }
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{   //整个首页的嵌套UITableView中的CELL
    UITableViewCell *cell = nil;
    if (indexPath.section == 0) {
        if(indexPath.row == 0)
        {
            //幻灯片
            static NSString *pageCellIdentifier = @"slidesCell";
            cell = [tableView dequeueReusableCellWithIdentifier:pageCellIdentifier];
            // Configure the cell...
            if(cell == nil)
            {
                
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:pageCellIdentifier];
                [cell.contentView addSubview:self.cntView];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        else if(indexPath.row == 1)
        {
            //当季热门
            static NSString *CellIdentifier = @"SeasonCell";
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                self.cell = cell;
            }
            [self seasonSetup:cell];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        else if(indexPath.row == 2) //由于结果NSInteger会被隐式转成NSUInteger导致结果出错
        {
            //专题看点
            static NSString *specialListIdentifier = @"okRecommendCell";
            cell = [tableView dequeueReusableCellWithIdentifier:specialListIdentifier];
            // Configure the cell...
            if(cell == nil)
            {
                
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:specialListIdentifier];
                //分割线
            }
            [self okRecommend:cell indexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
    else
    {
        
        //资讯
        //bable-
        NSDictionary *cellDic = _newsList[indexPath.row];
        if([[cellDic objectForKey:P_IS_TOPIC] isEqual: @(YES)]){//判断是否为“专题”CELL
            cell = [tableView dequeueReusableCellWithIdentifier:@"TopspeacialCellView"];//载入“专题”CELL的布局文件
            if(cell == nil)
            {
                cell = [[NSBundle mainBundle] loadNibNamed:@"TopspeacialCellView"  owner:self options:nil][0];
            }
//            [self cellSetup:cell index:indexPath.row];
//            [tableView setRowHeight:1005];
            TopSpecialCellViewController *topSpecialCell = [[TopSpecialCellViewController alloc] init];
            [topSpecialCell cellSetup:cell dic:cellDic index:indexPath.row];//载入“专题”CELL的构造方法
        }else{
        cell = [tableView dequeueReusableCellWithIdentifier:@"CommonCell"];
        // Configure the cell...
        if(cell == nil)
        {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CommonCell"  owner:self options:nil][0];
        }

        [self cellSetup:cell index:indexPath.row];
        }
    }
    NSAssert(cell != nil, @"specialMessageViewController cell is nil");
    return cell;
}


#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //单个资讯详情
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row >= self.newsList.count) {
        return;
    }
    if (indexPath.section == 1) {
        NSDictionary* dic = self.newsList[indexPath.row];
        if([[dic objectForKey:P_IS_TOPIC] isEqual: @(YES)]){//判断是否为专题
            
            TopSpecialDetailsPageTableViewController *sub = [[TopSpecialDetailsPageTableViewController alloc] init];
            sub.hidesBottomBarWhenPushed = YES;//不显示底部导航栏
            sub.topicId = [dic objectForKey:P_TOPIC_ID];
//            [sub langchApiData];
            
            [self.navController pushViewController:sub animated:YES];


        }else{
            NSString *url = [Common valueForKey:P_URL dic:dic];
        self.web = [[BableWebViewController alloc]initWithFrame:[Common shareInstance].contentFrameNoTabBar url:[Common getUrlByString:url]];
        self.web.hidesBottomBarWhenPushed = YES;
        self.web.target_id = [[Common valueForKey:@"id" dic:dic] intValue];
        self.web.type = @"NEWS";

        [self.navController pushViewController:_web animated:YES];
   
        }
    }
}






- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    UIImageView *firstDot = (UIImageView*)[scrollView.superview viewWithTag:30001];
    UIImageView *secondDot = (UIImageView*)[scrollView.superview viewWithTag:30002];
    if (scrollView.contentOffset.x == 320) {
        firstDot.image = [UIImage imageNamed:@"siftSideBar/dot_grey"];
        secondDot.image = [UIImage imageNamed:@"siftSideBar/dot_blue"];
    } else {
        firstDot.image = [UIImage imageNamed:@"siftSideBar/dot_blue"];
        secondDot.image = [UIImage imageNamed:@"siftSideBar/dot_grey"];
    }
}

#pragma mark - Tap
- (void)tapSeason:(UITapGestureRecognizer*)onTap
{
    NSLog(@"=====>SpecialMessageViewController=====>tapSeason: %@",onTap);
    NSArray *List = nil;
    int index = nil;
    if ([onTap.view.accessibilityValue  isEqualToString: @"season"]) {
        List = [Common valueForKey:P_SEASONLIST dic:self.specialDataDic];
        index = onTap.view.tag - 10000;
    } else if ([onTap.view.accessibilityValue isEqualToString:@"OK"]) {
        List = [Common valueForKey:P_OKLIST dic:self.specialDataDic];
        index = onTap.view.tag - 20000;
    }
    [self jump:List index:index];
}

- (void)tapRecommend:(UITapGestureRecognizer*)onTap
{
    NSLog(@"=====>SpecialMessageViewController=====>tapRecommend: %@",onTap);
}

#pragma mark - Private
- (void)jump:(NSArray*)List index:(int)index
{
    NSDictionary *seasonDic = List[index];
    NSString *url = [Common valueForKey:P_URL dic:seasonDic];
    NSString *type = [Common valueForKey:P_TYPE dic:seasonDic];
    NSString *ref_id = [Common valueForKey:P_V2_REF_ID dic:seasonDic];
        if ([type isEqualToString:@"STORE"]) {
            SportsDetailViewController *storeDetailCtrl = [[SportsDetailViewController alloc] init];
            storeDetailCtrl.target_id = [ref_id intValue];
            storeDetailCtrl.hidesBottomBarWhenPushed = YES;
            [self.navController pushViewController:storeDetailCtrl animated:YES];
            
        } else if ([type isEqualToString:@"GOODS"]) {
            GoodDetailViewController *goodDetailCtrl = [[GoodDetailViewController alloc] init];
//            GoodDetailViewController *goodDetailCtrl = [[GoodDetailViewController alloc]initWithFrame:self.view.frame style:UITableViewStylePlain navigationBarHeight:0];
            goodDetailCtrl.goodId = [ref_id intValue];
            goodDetailCtrl.hidesBottomBarWhenPushed = YES;
//            UIView *navView = [TransforController shardeInstanceOfNavigationBarCoverViewWithY:0];
//            [goodDetailCtrl.view addSubview:navView];
//            [goodDetailCtrl.tableView.superview addSubview:navView];
//            [goodDetailCtrl.tableView setFrame:CGRectMake(0, 45, 320, 523)];
            goodDetailCtrl.instance_navigation_temp = self.navController;
            [goodDetailCtrl.view setFrame:self.view.bounds];
//            [goodDetailCtrl.view insertSubview:navView aboveSubview:goodDetailCtrl.tableView];
            [self.navController pushViewController:goodDetailCtrl animated:YES];
            
        } else if ([type isEqualToString:@"LIST"]) {
            NSArray *api_req = [url componentsSeparatedByString:@"/"];
            if (api_req.count >1) {
                NSString *name = [Common valueForKey:P_NAME dic:seasonDic];
                CommonCellViewController *commonCellCtrl = [[CommonCellViewController alloc] init];
                commonCellCtrl.isDisplayTopMenu = false;
                commonCellCtrl.title = name;
                commonCellCtrl.is_load_more = @"NO";
                commonCellCtrl.API_REQ = [NSArray arrayWithArray:api_req];
                commonCellCtrl.hidesBottomBarWhenPushed = YES;
                [self.navController pushViewController:commonCellCtrl animated:YES];
            }
        } else if ([type isEqualToString:@"URL"]) {
            WebIOS *web = [[WebIOS alloc]initWithFrame:[Common shareInstance].contentFrameNoTabBar url:[Common getUrlByString:url]];
            web.target_id = [[Common valueForKey:@"id" dic:seasonDic] intValue];
            web.type = @"NEWS";
            web.hidesBottomBarWhenPushed = YES;
            [self.navController pushViewController:web animated:YES];
        } else if ([type isEqualToString:@"MOVIE"]) {
            MovieViewController *listViewCtrl = [[MovieViewController alloc] initWithFrame:[Common shareInstance].contentFrameNoTabBar style:UITableViewStylePlain];
            listViewCtrl.type = 8;
            listViewCtrl.hidesBottomBarWhenPushed = YES;
            [self.navController pushViewController:listViewCtrl animated:YES];
        } else if ([type isEqualToString:@"NEWS"]) {
            int ID = [[Common valueForKey:P_V2_REF_ID dic:seasonDic] intValue];
            NSString *url = [NSString stringWithFormat:@"%@%@%d",@"http://api.okhaolvxing.com/okhaolvxing/index.php",@"/ApiNewsRelease/getContent?id=",ID];
            WebIOS *web = [[WebIOS alloc]initWithFrame:[Common shareInstance].contentFrameNoTabBar url:[Common getUrlByString:url]];
            web.target_id = [[Common valueForKey:@"id" dic:seasonDic] intValue];
            web.type = @"NEWS";
            web.hidesBottomBarWhenPushed = YES;
            [self.navController pushViewController:web animated:YES];
        }

}

#pragma mark delegate
-(void)refreshSiftCell:(NSMutableArray*)tagsSelected typeList:(NSMutableArray*)typesSelected distance:(NSString*)distance areasSelected:(NSMutableArray*)areasSelected
{
    NSLog(@"%s",__FUNCTION__);
    SiftCellViewController *seletedCellView = [[SiftCellViewController alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 65) style:UITableViewStylePlain];
    seletedCellView.tagsList = tagsSelected;
    seletedCellView.typesList = typesSelected;
    seletedCellView.areasList = areasSelected;
    seletedCellView.distance = distance;
    seletedCellView.hidesBottomBarWhenPushed = YES;
    [self.navController pushViewController:seletedCellView animated:YES];
}

- (void)resetPullTableViewState
{
    [self setPullTableIsRefreshing:NO];
    [self setPullTableIsLoadMore:NO];
}

#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    //下拉刷新
    self.newsList = nil;
    self.messageIndex = 1;
    [[ProtocolManager shareInstance] getSlidesAndSpecial:self selector:@selector(didFinishGetSlidesAndSpecial:)];
    [[ProtocolManager shareInstance] getHomePageNewsList:20 beginNo:0 target:self selector:@selector(didFinishGetNewsList:)];
    if([Common checkNetReachable])
    {
        [self setPullRefreshDate:[NSDate date]];
    }
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    //加载更多
    [[ProtocolManager shareInstance] getHomePageNewsList:20 beginNo:_messageIndex target:self selector:@selector(didFinishGetNewsList:)];
}


-(void)pageViewDidClickedWithPageNumber:(NSInteger)pageNumber
{
    NSLog(@"pageViewDidClickedWithPageNumber:%d",pageNumber);
    NSArray *List = [Common valueForKey:P_SLIDESLIST dic:self.specialDataDic];
    [self jump:List index:pageNumber];
}

-(void)pageViewWillBeginDraging
{
    NSLog(@"pageViewWillBeginDraging");
    [self pageEndRoll];
}

-(void)pageViewDidEndDraging
{
    NSLog(@"pageViewDidEndDraging");
    [self pageStartRoll];
}

#pragma mark HttpRequest delegate
-(void)requestDidFinish:(ASIHTTPRequest *)request
{
    NSDictionary *userDic =  request.userInfo;
    NSString* type = [userDic objectForKey:@"type"];
    if ([type isEqualToString:@"specialImage"]) {
        int index = [[userDic objectForKey:@"index"] intValue];
        NSLog(@"*******index = %d",index);
        NSString *path = [request.downloadCache pathToCachedResponseDataForURL:request.url];
        if([path length] == 0)
        {
            return;
        }
        if([request didUseCachedResponse])
        {
            NSLog(@"use chace");
        }
        UIImage *img = [UIImage imageWithContentsOfFile:path];
        if(img != nil)
        {
            [self.pageScroll setImageForImageViewByIndex:index image:img];
        }
    }
    else if([type isEqualToString:@"messageIcon"]) {
        int index = [[userDic objectForKey:@"index"] intValue];
        [self reloadRowIndexInSection:0 row:index+1];
    }
}
-(void)requestDidFail:(ASIHTTPRequest *)request
{
    
}
-(void)queueDidFinish:(ASINetworkQueue *)queue
{
    NSDictionary* dic = queue.userInfo;
    int queueId = [[dic objectForKey:@"id"] intValue];
    if (queueId == self.specialImgQueueID) {
        if([Common checkNetReachable])
        {
            [self setPullRefreshDate:[NSDate date]];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)webViewPushDiscloseDetailsWithWebView{
//    webViewPushDiscloseDetailsViewController *discloseDetails = [[webViewPushDiscloseDetailsViewController alloc] init];
//    [[self.web.discloseDetails alloc] init];
//    [self.web.navigationController pushViewController:_web.discloseDetails animated:YES];
//    NSLog(@"_web.discloseDetails = %@ !!!!!!!!!!!!!!!!!!",_web.discloseDetails);
//    NSLog(@"self.web.navigationController = %@ !!!!!!!!!!",self.web.navigationController);
    NSLog(@"132212353446");
}


@end
